package com.polaris.live.utils.sensor

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.polaris.live.common.util.SystemUtils
import kotlin.math.abs

/**
 * 摇一摇
 *
 * @author Created by lucas on 2023/10/25 16:03
 * @since 1.0.0
 */
abstract class SensorModuleHelper(
    protected val mContext: AppCompatActivity
) : LifecycleEventObserver,
    SensorEventListener {

    private val mSensorManager: SensorManager?
    protected var mIsShowed = false

    init {
        mContext.lifecycle.addObserver(this)
        mSensorManager = mContext.getSystemService(Context.SENSOR_SERVICE) as? SensorManager
    }

    override fun onSensorChanged(event: SensorEvent) {
        val type: Int = event.sensor.type
        if (type == Sensor.TYPE_ACCELEROMETER) {
            val values: FloatArray = event.values
            val x = values[0]
            val y = values[1]
            val z = values[2]
            if (!mIsShowed
                && (abs(x) > 17 || abs(y) > 17 || abs(z) > 17)
            ) {
                if (showSetting()) {
                    mIsShowed = true
                    SystemUtils.vibrate(mContext)
                }
            }
        }
    }

    override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_START -> {
                mSensorManager?.registerListener(
                    this,
                    mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                    SensorManager.SENSOR_DELAY_UI
                )
            }
            Lifecycle.Event.ON_STOP -> {
                mSensorManager?.unregisterListener(this)
            }
            else -> {
                //ignore
            }
        }
    }

    abstract fun showSetting(): Boolean

}